/**
 * Sooying.cn Inc.
 * Copyright (c) 2010-2015 All Rights Reserved.
 */
package com.dundun.SSO.core.base;

import com.dundun.SSO.pojo.Constant;
import com.dundun.SSO.pojo.ResponseBean;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;

/**
 *
 *
 *
 *
 */
@Controller
public class TemplateController extends BaseController {

    Logger logger = LoggerFactory.getLogger(TemplateController.class);

    public void execute(HttpServletRequest request, ResponseBean response,
                        ControllerCallBack callBack) {

        try {
            // 1 执行参数验证
            callBack.doCheck(response);
            // 2执行业务处理
            callBack.doOperation(response);

        } catch (ParamaterConvertException e) {
            logger.error("TemplateController.execute:{}",e);
            response.setCode(Constant.PARAMETER_CONVERT_EXCEPTION.getCode());
            response.setMsg(e.getResultMsg());
        } catch (CommonBizException e) {
            logger.error("TemplateController.execute:{}",e);
            response.setCode(Constant.PARAMETER_ERROR.getCode());
            response.setMsg(e.getResultMsg());
        } catch (Exception e) {
            logger.error("TemplateController.execute:{}",e);
            response.setCode(Constant.UNKNOWN_ERROR.getCode());
            response.setMsg("系统异常");
        }
    }

    /**
     * 获取来源IP
     * 
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (!StringUtils.isBlank(ip) && ip.lastIndexOf(",") != -1) {
            int startIndex = ip.lastIndexOf(",") + 1;
            ip = ip.substring(startIndex).trim();
        }
        return ip;
    }

}
